package com.web.exiaodao.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.web.webstart.base.service.impl.BaseService;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.util.jpa.DynamicSpecifications;
import com.web.webstart.base.util.jpa.MyPage;
import com.web.webstart.base.util.jpa.SearchFilter;
import com.web.webstart.base.util.jpa.SearchFilter.Operator;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.XaUtil;
import com.web.exiaodao.business.entity.AutherLeaveMessage;
import com.web.exiaodao.business.repository.AutherLeaveMessageRepository;
import com.web.exiaodao.business.service.AutherLeaveMessageService;
import com.web.exiaodao.remote.vo.ArtInformationVo;
import com.web.exiaodao.remote.vo.AutherLeaveMessageVo;
import com.web.exiaodao.remote.vo.AutherWorksTableVo;
import com.web.exiaodao.remote.vo.UserVo;

@Service("AutherLeaveMessageService")
@Transactional(readOnly = false)
public class AutherLeaveMessageServiceImpl extends BaseService<AutherLeaveMessage> implements AutherLeaveMessageService {

	private static final Logger LOGGER = Logger.getLogger(AutherLeaveMessageServiceImpl.class);

	@Autowired
	private AutherLeaveMessageRepository autherLeaveMessageRepository;
	
	/**
	 * 查询单条AutherLeaveMessage信息
	 * //@param tId
	 * @return 返回单个AutherLeaveMessage对象
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<AutherLeaveMessage> findOne(Long modelId) throws BusinessException {
		AutherLeaveMessage obj = new AutherLeaveMessage();
		if(modelId != 0){
			obj = autherLeaveMessageRepository.findByIdAndStatusNot(modelId,XaConstant.Status.delete);
		}
		XaResult<AutherLeaveMessage> xr = new XaResult<AutherLeaveMessage>();
		if (XaUtil.isNotEmpty(obj)) {
			xr.setObject(obj);
			LOGGER.info("后台----->查询单个实体----->AutherLeaveMessage");
		} else {
			xr.error(XaConstant.Message.object_not_find);
			LOGGER.info(XaConstant.Message.object_not_find);
		}
		return xr;
	}

	/**
	 * 分页查询状态非status的AutherLeaveMessage数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象AutherLeaveMessage集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<AutherLeaveMessage>> findListNEStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示非删除的所有数据
			status = XaConstant.Status.delete;
		}
		filters.put("status", new SearchFilter("status", Operator.NE, status));
		Page<AutherLeaveMessage> page = autherLeaveMessageRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), AutherLeaveMessage.class), pageable);
		XaResult<Page<AutherLeaveMessage>> xr = new XaResult<Page<AutherLeaveMessage>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态不等于）----->AutherLeaveMessage");
		return xr;
	}

	/**
	 * 分页查询状态status的AutherLeaveMessage数据
	 * @param status
	 * @param filterParams
	 * @param pageable
	 * @return 返回对象AutherLeaveMessage集合
	 * @throws BusinessException
	 */
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public XaResult<Page<AutherLeaveMessage>> findListEQStatusByFilter(
			Integer status, Map<String, Object> filterParams, Pageable pageable) throws BusinessException {
		Map<String, SearchFilter> filters = SearchFilter.parse(filterParams);
		if(status == null){// 默认显示正常数据
			status = XaConstant.Status.valid;
		}
		filters.put("status", new SearchFilter("status", Operator.EQ, status));
		Page<AutherLeaveMessage> page = autherLeaveMessageRepository.findAll(DynamicSpecifications
				.bySearchFilter(filters.values(), AutherLeaveMessage.class), pageable);
		XaResult<Page<AutherLeaveMessage>> xr = new XaResult<Page<AutherLeaveMessage>>();
		xr.setObject(page);
		LOGGER.info("后台----->分页查询实体集合（状态等于）----->AutherLeaveMessage");
		return xr;
	}

	/**
	 * 保存AutherLeaveMessage信息
	 * @param model
	 * @return
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<AutherLeaveMessage> saveOrUpdate(AutherLeaveMessage model) throws BusinessException {
		AutherLeaveMessage obj = null;
		if(XaUtil.isNotEmpty(model.getId())){
			obj = autherLeaveMessageRepository.findOne(model.getId());
		}else{
			obj = new AutherLeaveMessage();
		}
	    obj.setLeaveMessageContent(XaUtil.isNotEmpty(model.getLeaveMessageContent()) ? model.getLeaveMessageContent() : obj.getLeaveMessageContent());
	    obj.setUserId(XaUtil.isNotEmpty(model.getUserId()) ? model.getUserId() : obj.getUserId());
	    obj.setWorksID(XaUtil.isNotEmpty(model.getWorksID()) ? model.getWorksID() : obj.getWorksID());
	    obj.setLeaveMessageContent(XaUtil.isNotEmpty(model.getLeaveMessageContent()) ? model.getLeaveMessageContent() : obj.getLeaveMessageContent());
		obj = autherLeaveMessageRepository.save(obj);
		XaResult<AutherLeaveMessage> xr = new XaResult<AutherLeaveMessage>();
		xr.setObject(obj);
		LOGGER.info("后台新增或编辑数据成功！");
		return xr;
	}

	/**
	 * 修改AutherLeaveMessage状态，可一次修改多条   3删除  -1锁定  1正常
	 * //@param userId
	 * @param modelIds
	 * @param status
	 * @return 返回AutherLeaveMessage对象
	 * @throws BusinessException
	 */
	@Transactional(rollbackFor = Exception.class)
	public XaResult<AutherLeaveMessage> multiOperate(
			String modelIds,Integer status) throws BusinessException {
		XaResult<AutherLeaveMessage> xr = new XaResult<AutherLeaveMessage>();
		if(status == null){
			status = XaConstant.Status.delete;
		}
		if(modelIds != null){
			String[] ids = modelIds.split(",");
			for(String id : ids){
				AutherLeaveMessage obj = autherLeaveMessageRepository.findByIdAndStatusNot(Long.parseLong(id),status);
				if (XaUtil.isNotEmpty(obj)) {
					obj.setStatus(status);
					obj = autherLeaveMessageRepository.save(obj);
				}
			}
		}
		LOGGER.info("批量修改数据状态成功！");
		return xr;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public XaResult<Page<AutherLeaveMessageVo>> findAutherLeaveMessageList(
			Pageable pageable, Map<String, Object> filterParams) throws BusinessException {
		StringBuffer sql = new StringBuffer("SELECT mes.id,u.`photo`,u.`mobile`,mes.`create_time`,mes.`leave_message_content`,wo.works_name,art.author_introduce,wo.works_price,u.user_name ");
		sql.append("FROM `tb_xa_autherleavemessage` mes ");
		sql.append("LEFT JOIN `tb_xa_user` u ON mes.`user_id` = u.`id` ");
		sql.append("LEFT JOIN `tb_xa_autherworkstable` wo  ON mes.`worksid` = wo.`id` ");
		sql.append("LEFT JOIN `tb_xa_artinformation` art ON wo.`autherid` = art.`id` ");
		sql.append("WHERE mes.status<>").append(XaConstant.Status.delete);
		StringBuffer sql1 = new StringBuffer("select count(*) ");
		sql1.append("FROM `tb_xa_autherleavemessage` mes ");
		sql1.append("LEFT JOIN `tb_xa_user` u ON mes.`user_id` = u.`id` ");
		sql1.append("LEFT JOIN `tb_xa_autherworkstable` wo  ON mes.`worksid` = wo.`id` ");
		sql1.append("LEFT JOIN `tb_xa_artinformation` art ON wo.`autherid` = art.`id` ");
		sql1.append("WHERE mes.status<>").append(XaConstant.Status.delete);
		//查询条件
		if(XaUtil.isNotEmpty(filterParams.get("LIKE_WorksID"))){
			sql.append(" AND wo.works_name ").append(" like '%").append(filterParams.get("LIKE_WorksID")).append("%' ");
			sql1.append(" AND wo.works_name ").append(" like '%").append(filterParams.get("LIKE_WorksID")).append("%' ");
		}
		sql.append(" ORDER BY mes.create_time desc");
		sql1.append(" ORDER BY mes.create_time desc");
		List<Object[]> objs = this.query(sql.toString(), pageable.getPageNumber()*pageable.getPageSize(), pageable.getPageSize());
		List<AutherLeaveMessageVo> vos = new ArrayList<AutherLeaveMessageVo>();
		for (Object[] obj : objs) {
			AutherLeaveMessageVo vo = new AutherLeaveMessageVo();
			UserVo userVo = new UserVo();
			AutherWorksTableVo wVo = new AutherWorksTableVo();
			ArtInformationVo aVo = new ArtInformationVo();
			vo.setId(Long.valueOf(obj[0].toString()));
			userVo.setPhoto(XaUtil.isEmpty(obj[1])?"":obj[1].toString());
			userVo.setMobile(XaUtil.isEmpty(obj[2])?"":obj[2].toString());
			vo.setCreateTime(XaUtil.isEmpty(obj[3])?"":obj[3].toString());
			vo.setLeaveMessageContent(XaUtil.isEmpty(obj[4])?"":obj[4].toString());
			wVo.setWorksName(XaUtil.isEmpty(obj[5])?"":obj[5].toString());
			aVo.setAuthorIntroduce(XaUtil.isEmpty(obj[6])?"":obj[6].toString());
			wVo.setWorksPrice(XaUtil.isEmpty(obj[7])?0:Double.valueOf(obj[7].toString()));
			userVo.setUserName(XaUtil.isEmpty(obj[8])?"":obj[8].toString());
			vo.setArtInformationVo(aVo);
			vo.setAutherWorksTableVo(wVo);
			vo.setUserVo(userVo);
			vos.add(vo);
		}
		List<Object[]> obj1=this.query(sql1.toString(), null, null);
		int count=Integer.parseInt(obj1.get(0)+"");	
		Page<AutherLeaveMessageVo> page= new MyPage<AutherLeaveMessageVo>(pageable.getPageNumber(),pageable.getPageSize(),vos,count);
		XaResult<Page<AutherLeaveMessageVo>> xr=new XaResult<Page<AutherLeaveMessageVo>>();
		xr.setObject(page);
		return xr;
	}
	
}
